#include <mpi.h>
#include <stdio.h>
#include "utils.h"


int main(int argc, char** argv) {
    int rank, size;
    int index[4] = {2, 5, 7, 8};                // 定义每个节点的邻居数
    //! 每个rank的邻居
    // rank 0 [1, 2]
    // rank 1 [0, 2, 3]
    // rank 2 [0]
    // rank 3 [1]                               //! 看起来是有向图?
    int edges[8] = {1, 2,  0, 2, 3,  0, 1,  1}; // 定义每个节点的邻居
    MPI_Comm graph_comm;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    //! 创建图拓扑
    // nnodes = 4, reorder = 0
    MPI_Graph_create(MPI_COMM_WORLD, 4, index, edges, 0, &graph_comm);

    //! 打印每个进程的邻居
    int nneighbors;
    MPI_Graph_neighbors_count(graph_comm, rank, &nneighbors);      // 获取当前rank的邻居数量
    int neighbors[nneighbors];
    MPI_Graph_neighbors(graph_comm, rank, nneighbors, neighbors);  // 获取当前rank的邻居rank编号

    // Process 0: Neighbors 1 2 
    // Process 1: Neighbors 0 2 3 
    // Process 2: Neighbors 0 1 
    // Process 3: Neighbors 1 
    printf("Process %d: Neighbors ", rank);
    for (int i = 0; i < nneighbors; i++) {
        printf("%d ", neighbors[i]);
    }
    printf("\n");

    //! 进行一些简单的通信，例如与第一个邻居通信
    if (nneighbors > 0) {
        int first_neighbor = neighbors[0];
        int message = rank;
        MPI_Send(&message, 1, MPI_INT, first_neighbor, 0, graph_comm);
        printf("Process %d sent message %d to first neighbor %d\n", rank, message, first_neighbor);

        int received_message;
        MPI_Recv(&received_message, 1, MPI_INT, first_neighbor, 0, graph_comm, MPI_STATUS_IGNORE);
        printf("Process %d received message %d from first neighbor %d\n", rank, received_message, first_neighbor);
    }

    MPI_Finalize();
    return 0;
}